find_program(wayland_scanner wayland-scanner)

execute_process(
    COMMAND pkg-config --variable=pkgdatadir wayland-protocols
    OUTPUT_VARIABLE wl_protocol_dir
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )

#wayland_scanner_code = generator(
#	wayland_scanner,
#	output: '@BASENAME@-protocol.c',
#	arguments: ['private-code', '@INPUT@', '@OUTPUT@'],
#)
#
#wayland_scanner_server = generator(
#	wayland_scanner,
#	output: '@BASENAME@-protocol.h',
#	arguments: ['server-header', '@INPUT@', '@OUTPUT@'],
#)

set(server_protocols
        ${wl_protocol_dir}/stable/xdg-shell/xdg-shell.xml
        ${wl_protocol_dir}/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml
        ${wl_protocol_dir}/staging/cursor-shape/cursor-shape-v1.xml
        ${wl_protocol_dir}/staging/drm-lease/drm-lease-v1.xml
        ${wl_protocol_dir}/staging/tearing-control/tearing-control-v1.xml
        ${CMAKE_CURRENT_SOURCE_DIR}/wlr-layer-shell-unstable-v1.xml
        ${CMAKE_CURRENT_SOURCE_DIR}/wlr-input-inhibitor-unstable-v1.xml
        ${CMAKE_CURRENT_SOURCE_DIR}/wlr-output-power-management-unstable-v1.xml
        )

#
#foreach xml : server_protocols
#	server_protos_src += wayland_scanner_code.process(xml)
#	server_protos_headers += wayland_scanner_server.process(xml)
#endforeach


set(server_protos_src )
set(server_protos_headers )
foreach(XML_FILE ${server_protocols})
    get_filename_component(BASENAME ${XML_FILE} NAME_WE)
    set(HEADER_FILE ${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}-protocol.h)
    set(C_FILE ${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}-protocol.c)

    add_custom_command(
        OUTPUT ${HEADER_FILE}
        COMMAND ${wayland_scanner} server-header ${XML_FILE} ${HEADER_FILE}
        DEPENDS ${XML_FILE}
        )

    add_custom_command(
        OUTPUT ${C_FILE}
        COMMAND ${wayland_scanner} private-code ${XML_FILE} ${C_FILE}
        DEPENDS ${XML_FILE}
        )

    list(APPEND server_protos_headers ${HEADER_FILE})
    list(APPEND server_protos_src ${C_FILE})
endforeach()

add_library(lib_server_protos
    STATIC
    ${server_protos_headers}
    ${server_protos_src}
    )
target_link_libraries(lib_server_protos
    PUBLIC
    PkgConfig::WAYLAND_SERVER
    )
target_include_directories(lib_server_protos
    PUBLIC
    ${CMAKE_CURRENT_BINARY_DIR}
    )


#lib_server_protos = static_library(
#	'server_protos',
#	server_protos_src + server_protos_headers,
#	dependencies: [wayland_server]
#)
#
#server_protos = declare_dependency(
#	link_with: lib_server_protos,
#	sources: server_protos_headers,
#)
